/**
 * 
 */
 
 var flag = 0;
 var url = null;
$(function() {
	
	$("#AC,#LOADING,#download").css("display", "none");
	$("#open_1").click(function() {
		$("#mask").css("display", "block");
	});
	$("#mask").hover(function() {
	}, function() {
		$("#mask").css("display", "none");
	});

	$(".langauaget").click(function() {
		$("#langauage1").html($(this).html());
		var lan = $(this).attr("id");
		$("#target").val(lan);
		$("#mask").css("display", "none");
		$(".left").attr("src", "image/arrow1.png");
		$("#starting").attr("class", "a-btn left");
		
		$("#starting").bind('click',function() {
			$("#starting").unbind('click');
			$("#AC").css("display", "none");
			$("#LOADING").css("display", "block");
			subFrm();
		});
	});
	//getSupportLan();
	
//	adddndListeners();

	$(document).on({
		dragleave : function(e) {
			e.preventDefault();
		},
		drop : function(e) {
			e.preventDefault();
		},
		dragenter : function(e) {
			e.preventDefault();
		},
		dragover : function(e) {
			e.preventDefault();
		}
	});

	/*var box = document.getElementById('dnd');
	box.addEventListener("drop", function(e) {
		e.stopPropagation();
		e.preventDefault();
		var fileList = e.dataTransfer.files;

		if (fileList.length == 0) {
			return false;
		}

		if (fileList[0].type.indexOf('pdf') === -1) {
			alert("请选择PDF文件!");
			return false;
		}

		var filename = fileList[0].name;

		var filesize = Math.floor((fileList[0].size) / 1024 / 1024);
		if (filesize > 200) {
			alert("文件大小不能超过200M.");
			return false;
		}

		showNext(filename);
		 xhr = new XMLHttpRequest();
		xhr.open("post", "upload.php", true);
		xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
		var fd = new FormData();
		fd.append('mypic', fileList[0]);
		xhr.send(fd); 
	}, false);*/

});

function getSupportLan(){
	$.ajax({
		type:'post',
		dataType:'json',
		url:'supportLanguage.do',
		success:function(data){
			if(data.success){
				$("#mask").empty();
				var str = "<ul>";
				for(var i = 0;i < data.language_cout;i++){
					str += "<li><a class=\"langauaget\" id=\"" + data.languages[i].language +  "\">" + data.languages[i].name + "</a></li>";
				}
				str += "</ul>";
				
				$("#mask").append(str);
			}
		},
		error:function(data){
			
		}
	});
}
  
function showNext(filename) {
	$("#mid_block").css("display", "none");
	$("#AC").css("display", "block");
	if(filename.length > 12){
		$("#filename").html(filename.substring(0,12) + "...");
	}else{
		$("#filename").html(filename);
	}
}
function subFrm() {
	var options = {
		dataType : 'json',
		iframe : false,
		clearForm:true,
		resetForm:true,
		//dataType:'json',
		beforeSubmit : function() {
			$("#processname").html("Uploading...");
		},
		uploadProgress : function(event, position, total, percentComplete) {
			$("#process").html(percentComplete + "%");
			//进度条旋軿
			var num = percentComplete * 3.6;
			if (num <= 180) {
				$("#loadright").css('transform', "rotate(" + num + "deg)");
			} else {
				$("#loadright").css('transform', "rotate(180deg)");
				$("#loadleft").css('transform',"rotate(" + (num - 180) + "deg)");
			}
		},
		success : function(data) {
			if (!data.success) {
				$("#processname").text("Translating...");
				$("#process").text(0);
				$("#LOADING").css("display", "none");
				$("#download").css("display", "block");
				alert("File upload failed!");
				window.location = window.location;
			} else {
				$("#processname").text("Translating...");
				$("#process").text("");
				schedule(data.docId);
			}
		},
		error : function(data) {
			alert("File upload failed!");
			window.location = window.location;
		}
	};
	$('#formwithAjax').ajaxSubmit(options);

	return false;
}

function isComplete(docid){
	
	$.ajax({
		type:'post',
		dataType:'json',
		data:{
			docId:docid
		},
		url:'GetTranslateStatus.do',
		success:function(data){
			if(data.success){
				$("#LOADING").css("display", "none");
				$("#download").css("display", "block");
				url = data.url;
				flag = 2;
			}else{
				flag = data.status;
			}
		},
		error:function(data){
			alert("Translation failed!");
			window.location = window.location;
		}
	});
	return flag;
}
function schedule(docid){
	var date = new Date();
	var time = date.getTime();
	var timesche = setInterval(function(){
		flag = isComplete(docid);
		if(flag != 0 && flag != 1){
		    clearInterval(timesche);
		    if(flag == 2){
					$("#download").click(function(){
							window.location.href= url;
					});
		    }else if(flag == -1){
					alert("Translation failed!");
					window.location = window.location;
		    }else if(flag == -2){
					alert("It's not a PDF file,please select a PDF file!");
					window.location = window.location;
		    }else if(flag == -3){
					alert("Encrypted or protected document is not supported!");
					window.location = window.location;
		    }

		}
		var date1 = new Date();
    var time2 = date1.getTime() - time;
    
    if(time2 / 1000 > 60 * 10){
    	clearInterval(timesche);
    	alert("Translation failed!");
    	window.location = window.location;
    }
	},1000);
}

function selectFile() {
	$("#slct-a").click();
}

function inputchange(filename){
		var suffix = filename.substring(filename.lastIndexOf(".") + 1);
		if("pdf" != suffix.toLowerCase()){
			alert("Please select a PDF file!");
		}else{
			showNext(filename);
		}
}

function adddndListeners() {
	var container = document.getElementById("dnd");
	var fileList = document.getElementById("fileList");
	// 拖拽进入目标对象时触卿
	container.addEventListener("dragenter", function(event) {
		fileList.innerHTML = '';
		event.stopPropagation();
		event.preventDefault();
	}, false);
	// 拖拽在目标对象上时触卿
	container.addEventListener("dragover", function(event) {
		event.stopPropagation();
		event.preventDefault();
	}, false);
	// 拖拽结束时触卿
	container.addEventListener("drop", handleDrop, false);
}

function handleDrop(event) {
	// 获取拖拽的文件列蟿
	var files = event.dataTransfer.files;
	event.stopPropagation();
	event.preventDefault();
//	var fileList = document.getElementById("fileList");
	// 展示文件缩略图，文件名和上传进度，上传文乿
	for (var i = 0; i < files.length; i++) {
		var file = files[i];
		/*var li = document.createElement('li');
		var progressbar = document.createElement('div');
		var img = document.createElement('img');
		var name = document.createElement('span');
		progressbar.className = "progressBar";
		img.src = files[i].getAsDataURL();
		img.width = 32;
		img.height = 32;
		name.innerHTML = file.name;
		li.appendChild(img);
		li.appendChild(name);
		li.appendChild(progressbar);
		fileList.appendChild(li);*/
		$("#mid_block").css("display", "none");
		$("#AC").css("display", "block");
		$("#filename").html(file.name);
		$("#starting").click(function() {
			uploadFile(file);
		});
	}
}


function uploadFile(file) {
	var xhr = new XMLHttpRequest();
	var upload = xhr.upload;
	
	// 设置上传文件相关的事件处理函擿
	upload.addEventListener("progress", uploadProgress, false);
	upload.addEventListener("load", uploadSucceed, false);
	upload.addEventListener("error", uploadError, false);
	// 上传文件
	xhr.open("post", "UploadPDF.do", true);
	xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
	xhr.setRequestHeader("Content-type", "multipart/form-data;"); 
	var fd = new FormData();
	fd.append('sampleFile', fileList[0]);
	xhr.send(fd);
}

function uploadProgress(event) {
	if (event.lengthComputable) {
		// 将进度换算成百分歿
		var percentage = Math.round((event.loaded * 100) / event.total);
		console.log("percentage:" + percentage);
		$("#process").html(percentage);
		var num = percentage * 3.6;
		if (num <= 180) {
			$("#loadright").css('transform', "rotate(" + num + "deg)");
		} else {
			$("#loadright").css('transform', "rotate(180deg)");
			$("#loadleft").css('transform',"rotate(" + (num - 180) + "deg)");
		}
	}
}
function uploadSucceed(event) {
	$("#processname").text("Translating...");
	$("#process").text(0);
	$("#LOADING").css("display", "none");
	$("#download").css("display", "block");
	var link = window.location.href + data.data;
	$("#download").click(function(){
		window.location.href= link;
	});
}
function uploadError(error) {
	alert("error: " + error);
}